package com.qf.controller;


import ch.qos.logback.core.rolling.helper.IntegerTokenConverter;
import com.alipay.api.internal.util.AlipaySignature;
import com.qf.pojo.Cart;
import com.qf.service.OrderService;
import com.qf.utils.AlipayTools;
import com.qf.utils.Constant;
import com.qf.utils.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @GetMapping("/delByOrderId/{orderId}")
    public ResultMsg delByOrderId(@PathVariable String orderId) {
        return orderService.delByOrderId(orderId);
    }

    @GetMapping("/findAll")
    public ResultMsg findAll(HttpServletRequest request) {
        return orderService.findAll(request);
    }

    @PostMapping("/add")
    public ResultMsg add(@RequestBody Map<String, Object> map, HttpServletRequest request) {
        return orderService.add((ArrayList<Object>) map.get("list"), (String) map.get("remark"), request);
    }

    @GetMapping("/findOne/{orderId}")
    public ResultMsg findOne(@PathVariable String orderId) {
        return orderService.findOne(orderId);
    }

    @GetMapping("/updateStatusSync")
    public String updateStatusSync(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("http://localhost:8080/#/myorders");
        return null;
    }

    @PostMapping("/updateStatusAsync")
    public ResultMsg updateStatusAsync(HttpServletRequest request) {
        try {
            Map<String, String> paramsMap = AlipayTools.convert(request);  //将异步通知中收到的所有参数都存放到 map 中
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayTools.publicKey, "utf-8", "RSA2"); //调用SDK验证签名
            if (signVerified) {
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商家自身业务处理，校验失败返回failure
                //修入订单的支付状态：支付的状态/支付的时间/支付的订单信息
                ResultMsg resultMsg = orderService.updateStatus(paramsMap.get("subject"));
                resultMsg.setCode(100);
                return resultMsg;

            } else {
                // TODO 验签失败则记录异常日志，并在response中返回failure.
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.FAILED(Constant.LZY + 1, "我也不知道出啥错误了");
    }
}
